package com.kongyz.registry;

import com.kongyz.client.ConnectManage;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * @author kongyz
 * @date 2018/8/7 20:59
 * @Description: 服务发现类
 */
public class ServiceDiscovery {
    private final Logger logger=LoggerFactory.getLogger(this.getClass());
    /**
     * 类似计数器的一个功能
     * 能够使一个线程在等待另外一些线程完成各自工作之后，再继续执行
     */
    private CountDownLatch latch=new CountDownLatch(1);

    /**
     * 1、保证了不同线程对这个变量进行操作时的可见性，即一个线程修改了某个变量的值，这新值对其他线程来说是立即可见的。
     * 2、禁止进行指令重排序。
     * https://www.cnblogs.com/dolphin0520/p/3920373.html
     */
    private volatile List<String> dataList=new ArrayList<String>();

    private String registryAddress;
    private ZooKeeper zooKeeper;

    public ServiceDiscovery(String registryAddress) {
        this.registryAddress = registryAddress;
        this.zooKeeper = connectServer();
        if(zooKeeper!=null){
            watchNode(zooKeeper);
        }
    }

    /**
     * 创建连接
     * @return
     */
    private ZooKeeper connectServer(){
        ZooKeeper zk=null;
        try {
            zk=new ZooKeeper(registryAddress, Constant.ZK_SESSION_TIMEOUT, new Watcher() {
                public void process(WatchedEvent watchedEvent) {
                    if(watchedEvent.getState()==Event.KeeperState.SyncConnected){
                        latch.countDown();
                    }
                }
            });
            latch.await();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return zk;
    }

    /**
     * 节点数据
     * @param zk
     */
    private void watchNode(final ZooKeeper zk){
        try {
            //1、获取所有的数据节点
            List<String> nodeList=zk.getChildren(Constant.ZK_REGISTRY_PATH, new Watcher() {
                @Override
                public void process(WatchedEvent watchedEvent) {
                    if(watchedEvent.getType()==Event.EventType.NodeChildrenChanged){
                        watchNode(zk);
                    }
                }
            });
            //2、获取这些数据节点上的数据，并写入到列表中
            List<String> dataList=new ArrayList<String>();
            for (String node:nodeList){
                byte[] bytes=zk.getData(Constant.ZK_REGISTRY_PATH+"/"+node,false,null);
                dataList.add(new String(bytes));
            }
            //3、赋值给具备可见性的全局变量
            this.dataList=dataList;

            //4、更新服务连接
            UpdateConnectedServer();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (KeeperException e) {
            e.printStackTrace();
        }
    }

    private void UpdateConnectedServer(){
        ConnectManage.getInstance().updateConnectedServer(this.dataList);
    }

    public void stop(){
        if(zooKeeper!=null){
            try {
                zooKeeper.close();
            }catch (InterruptedException e){
                logger.error("",e);
            }
        }
    }

}
